<?php

namespace Index\Controller;

use Think\Controller;
use Index\ViewModel;
use Index\Service;

/**
 * 说明：号码管理控制器
 * 作者：王楠
 * 创建日期：2017-09-15
 */
class NumberController extends CommonController {

    /**
     * 号码列表
     */
    public function numberlist() {
	$level_enum = getenumbykey('usermembernum_level');
	$level_arr = getarrbyenum($level_enum);
	$type_enum = getenumbykey('usermembernum_type');
	$type_arr = getarrbyenum($type_enum);
	$state_enum = getenumbykey('usermembernum_state');
	$state_arr = getarrbyenum($state_enum);
	$app_code = $this->app_code;
	$type = trim(I('ddltype'));
	$state = trim(I('ddlstate'));
	$begintime = trim(I('txtbegintime'));
	$endtime = trim(I('txtendtime'));
	$keyword = trim(I('txtkeyword'));
	$appcode = trim(I('ddlapp'));
	if (!empty($app_code)) {
	    $map['app_flag'] = $app_code;
	} else {
	    if (!empty($appcode)) {
		$map['app_flag'] = $appcode;
	    }
	}
	if (!empty($type)) {
	    $map['num_flag'] = $type;
	}
	if (!empty($state)) {
	    $map['state'] = $state;
	}
	if (!empty($begintime) || !empty($endtime)) {
	    if (!empty($begintime) && !empty($endtime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), strtotime($endtime) + 60));
	    } else if (!empty($begintime)) {
		$map['ctime'] = array('between', array(strtotime($begintime), time() + 60));
	    } else if (!empty($endtime)) {
		$map['ctime'] = array('between', array(0, strtotime($endtime) + 60));
	    }
	}
	if (!empty($keyword)) {
	    $where['chat_usermembernum.user_id'] = array('eq', $keyword);
	    $where['_logic'] = 'or';
	    $map['_complex'] = $where;
	}
	$viewModel = new ViewModel\UsermembernumViewModel();
	$total = $viewModel->where($map)->count();
	$row = '10';
	$page = new Service\PageService($total, $row);
	$fpage = $page->fpage();
	$field = array(
	    'id', 'user_id', 'state', 'num_flag', 'stime', 'app_flag', 'start_id', 'end_id', 'ctime', 'user_uid', 'user_logo', 'user_name', 'user_sex', 'user_phone'
	);
	$data = $viewModel->where($map)->limit($page->listfirst, $page->listRows)->field($field)->order('ctime desc, id desc')->select();
	foreach ($data as $key => $value) {
	    $data[$key]['number'] = $value['user_id'];
	    $data[$key]['number_section'] = $value['start_id'] . '&nbsp;至&nbsp;' . $value['end_id'] . '&nbsp;' . $level_enum[strlen($value['start_id'])];
	    $data[$key]['number_type_text'] = $type_enum[$value['num_flag']];
	    $data[$key]['stime'] = empty($value['stime']) ? '' : date('Y-m-d H:i', $value['stime']);
	    $data[$key]['state_text'] = $state_enum[$value['state']];
	    $data[$key]['ctime'] = date('Y-m-d H:i', $value['ctime']);
	}
	$search = array('appsel' => $appcode, 'typesel' => $type, 'statesel' => $state, 'keyword' => $keyword, 'begintime' => $begintime, 'endtime' => $endtime);
	$this->assign(array(
	    'data' => $data,
	    'fpage' => $fpage,
	    'total' => $total,
	    'search' => $search,
	    'typearr' => $type_arr,
	    'statearr' => $state_arr,
	    'app_code' => $app_code,
	    'apparr' => $this->getapplist(),
	));
	$this->display();
    }

    /**
     * 号码详情、修改号码、创建号码、清除号码
     */
    public function numberadd() {
	$section_state_enum = getenumbykey('usernumsection_state');
	$level_enum = getenumbykey('usermembernum_level');
	$operate = I('type', '1');
	$id = I('id', '0');
	$columnname = $operate == '1' ? '添加号码' : '清除号码';
	if (empty($id)) {
	    $model = M('chat_usernumsection');
	    $section = $model->where(array('state' => array('neq', '5')))->order('id asc')->select();
	    $section_arr = array();
	    foreach ($section as $key => $value) {
		$diff = ($value['end_id'] + 1) - $value['start_id'];
		if ($operate == '1') {
		    $valid = $value['state'] == '2' ? '（大概需要【' . getuitime(($diff / 550), 'cn') . '】时间创建）' : '（' . $section_state_enum[$value['state']] . '）';
		} else {
		    $valid = $value['state'] == '3' ? '（大概需要【' . getuitime(($diff / 550), 'cn') . '】时间清除）' : '（' . $section_state_enum[$value['state']] . '）';
		}
		$item = array('value' => $value['id'], 'text' => ($value['start_id'] . '&nbsp;至&nbsp;' . $value['end_id'] . '&nbsp;&nbsp;&nbsp;' . $level_enum[strlen($value['start_id'])] . $valid));
		if ($operate == '1') {
		    $item['disabled'] = $value['state'] == '2' ? "" : "disabled='disabled'";
		} else {
		    $item['disabled'] = $value['state'] == '3' ? "" : "disabled='disabled'";
		}
		array_push($section_arr, $item);
	    }
	    $this->assign(array(
		'operate' => $operate,
		'sectionarr' => $section_arr,
	    ));
	    $this->assign('columnname', $columnname);
	    $this->display();
	    die;
	}
	$type_enum = getenumbykey('usermembernum_type');
	$type_arr = getarrbyenum($type_enum);
	$state_enum = getenumbykey('usermembernum_state');
	$state_arr = getarrbyenum($state_enum);
	if (!empty($id)) {
	    $columnname = $operate == '1' ? '号码详情' : '修改号码';
	    $viewModel = new ViewModel\UsermembernumViewModel();
	    $data = $viewModel->where(array('id' => $id))->find();
	    $number = $data['user_id'];
	    $state = $data['state'];
	    $state_text = $state_enum[$data['state']];
	    $type = $data['num_flag'];
	    $type_text = $type_enum[$data['num_flag']];
	    $number_section = $data['start_id'] . '&nbsp;至&nbsp;' . $data['end_id'] . '&nbsp;' . $level_enum[strlen($data['start_id'])];
	    $stime = empty($data['stime']) ? '' : date('Y-m-d H:i', $data['stime']);
	    $app_flag = $data['app_flag'];
	    $app_name = $data['app_name'];
	    $start_id = $data['start_id'];
	    $end_id = $data['end_id'];
	    $ctime = date('Y-m-d H:i', $data['ctime']);
	    $user_uid = $data['user_uid'];
	}
	foreach ($type_arr as $key => $value) {
	    if ($type == $value['value']) {
		$type_arr[$key]['selected'] = "selected='selected'";
	    }
	}
	foreach ($state_arr as $key => $value) {
	    if ($state == $value['value']) {
		$state_arr[$key]['selected'] = "selected='selected'";
	    }
	}
	$this->assign(array(
	    'operate' => $operate,
	    'id' => $id,
	    'data' => $data,
	    'number' => $number,
	    'number_section' => $number_section,
	    'type' => $type,
	    'type_text' => $type_text,
	    'stime' => $stime,
	    'app_code' => $app_flag,
	    'app_name' => $app_name,
	    'state' => $state,
	    'state_text' => $state_text,
	    'ctime' => $ctime,
	));
	$this->assign('columnname', $columnname);
	$this->assign('typearr', $type_arr);
	$this->assign('statearr', $state_arr);
	$this->display();
    }

    /**
     * 修改号码提交
     * @return type
     */
    public function numberupdatesubmit() {
	if (!IS_POST) {
	    $this->error('非法访问！');
	    die;
	}
	$app_code = $this->app_code;
	$id = I('id', '0');
	$type = trim(I('type', '0'));
	$state = trim(I('state', '0'));
	$model = M('chat_usermembernum');
	$data = array();
	if (!empty($type)) {
	    $data['num_flag'] = $type;
	}
	if (!empty($state)) {
	    $data['state'] = $state;
	}
	if (empty($id)) {
	    $response = array('ret' => '1002', 'code' => '无效的操作！');
	    return $this->ajaxReturn($response, 'json');
	}
	if ($model->where(array('id' => $id))->save($data)) {
	    $response = array('ret' => '1001', 'code' => '修改成功！');
	} else {
	    $response = array('ret' => '1001', 'code' => '修改成功！');
	}
	return $this->ajaxReturn($response, 'json');
    }

    /**
     * 创建号码提交
     * @return type
     */
    public function numbercreatesubmit() {
	if (!IS_POST) {
	    $this->error('非法访问！');
	    die;
	}
	$admin_id = $this->admin_id;
	$app_code = $this->app_code;
	$id = I('id', '0');
	$prettynumber = I('prettynumber');
	$prettynumber_arr = array();
	if (!empty($prettynumber)) {
	    $prettynumber_arr = explode(' ', $prettynumber);
	}
	if (empty($id)) {
	    $response = array('ret' => '1002', 'code' => '无效的操作！');
	    return $this->ajaxReturn($response, 'json');
	}
	$sectionModel = M('chat_usernumsection');
	$numberModel = M('chat_usermembernum');
	$sectionModel->startTrans();
	$numberModel->startTrans();
	$section = $sectionModel->where(array('id' => $id, 'state' => '2'))->find();
	if (empty($section)) {
	    $response = array('ret' => '1002', 'code' => '未找到选中的号码区间！');
	    return $this->ajaxReturn($response, 'json');
	}
	$start_id = $section['start_id'];
	$end_id = $section['end_id'];
	$number_count = $numberModel->where(array('user_id' => array('between', $start_id, $end_id)))->count();
	$i = 0;
	if ($number_count < (($end_id + 1) - $start_id)) {
	    $numbers = array();
	    if (!empty($number_count)) {
		$numbers = $numberModel->where(array('user_id' => array('between', $start_id, $end_id)))->field('id,user_id')->select();
	    }
	    for ($index = $start_id; $index < ($end_id + 1); $index++) {
		$exist = 0;
		if (!empty($numbers)) {
		    foreach ($numbers as $key => $value) {
			if ($index == $value['user_id']) {
			    $exist = 1;
			    break;
			}
		    }
		}
		if (!empty($exist)) {
		    continue;
		}
		$type = '1';
		if (!empty($prettynumber_arr)) {
		    $search = array_search($index, $prettynumber_arr);
		    $type = $search > -1 ? '2' : '1';
		}
		$data = array(
		    'user_id' => $index,
		    'state' => '1',
		    'num_flag' => $type,
		    'start_id' => $start_id,
		    'end_id' => $end_id,
		    'ctime' => time(),
		);
		$numberModel->add($data);
		$i++;
	    }
	} else {
	    $i = 1;
	}
	if (!empty($i)) {
	    $sectionModel->where(array('id' => $id))->save(array('state' => '3', 'use_admin_id' => $admin_id));
	    $sectionModel->where(array('start_id' => array('gt', $end_id), 'state' => array('lt', '3')))->limit(1)->order('start_id asc')->save(array('state' => '2'));
	    $sectionModel->commit();
	    $numberModel->commit();
	    $response = array('ret' => '1001', 'code' => '创建成功！');
	    return $this->ajaxReturn($response, 'json');
	} else {
	    $sectionModel->rollback();
	    $numberModel->rollback();
	    $response = array('ret' => '1002', 'code' => '创建失败！');
	    return $this->ajaxReturn($response, 'json');
	}
    }

    /**
     * 删除号码提交
     * @return type
     */
    public function numberdeletesubmit() {
	if (!IS_POST) {
	    $this->error('非法访问！');
	    die;
	}
	$admin_id = $this->admin_id;
	$app_code = $this->app_code;
	$id = I('id', '0');
	if (empty($id)) {
	    $response = array('ret' => '1002', 'code' => '无效的操作！');
	    return $this->ajaxReturn($response, 'json');
	}
	$sectionModel = M('chat_usernumsection');
	$numberModel = M('chat_usermembernum');
	$sectionModel->startTrans();
	$numberModel->startTrans();
	$section = $sectionModel->where(array('id' => $id, 'state' => '3'))->find();
	if (empty($section)) {
	    $response = array('ret' => '1002', 'code' => '未找到选中的号码区间！');
	    return $this->ajaxReturn($response, 'json');
	}
	$start_id = $section['start_id'];
	$end_id = $section['end_id'];
	$number_count = $numberModel->where(array('user_id' => array('between', $start_id, $end_id), 'state' => '2'))->count();
	$i = 0;
	if ($number_count < (($end_id + 1) - $start_id)) {
	    $numbers = array();
	    if (!empty($number_count)) {
		$numbers = $numberModel->where(array('user_id' => array('between', $start_id, $end_id), 'state' => '2'))->field('id,user_id')->select();
	    }
	    for ($index = $start_id; $index < ($end_id + 1); $index++) {
		$exist = 0;
		if (!empty($numbers)) {
		    foreach ($numbers as $key => $value) {
			if ($index == $value['user_id']) {
			    $exist = 1;
			    break;
			}
		    }
		}
		if (!empty($exist)) {
		    continue;
		}
		$numberModel->where(array('user_id' => $index))->delete();
		$i++;
	    }
	} else {
	    $i = 1;
	}
	if (!empty($i)) {
	    $sectionModel->where(array('id' => $id))->save(array('state' => '2', 'use_admin_id' => $admin_id));
	    $section = $sectionModel->where(array('state' => '2'))->order('start_id asc')->find();
	    if (!empty($section)) {
		$sectionModel->where(array('start_id' => array('gt', $section['end_id']), 'state' => '2'))->save(array('state' => '1'));
	    }
	    $sectionModel->commit();
	    $numberModel->commit();
	    $response = array('ret' => '1001', 'code' => '清除成功！');
	    return $this->ajaxReturn($response, 'json');
	} else {
	    $sectionModel->rollback();
	    $numberModel->rollback();
	    $response = array('ret' => '1002', 'code' => '清除失败！');
	    return $this->ajaxReturn($response, 'json');
	}
    }

    /**
     * 纠正号码提交（线下使用）
     * @return type
     */
    public function numbercorrectsubmit() {
	$id = I('id', '0');
	if (empty($id)) {
	    $response = array('ret' => '1002', 'code' => '无效的操作！');
	    return $this->ajaxReturn($response, 'json');
	}
	$sectionModel = M('chat_usernumsection');
	$numberModel = M('chat_usermembernum');
	$userinfoModel = M('chat_userinfo');
	$sectionModel->startTrans();
	$numberModel->startTrans();
	$userinfoModel->startTrans();
	$section = $sectionModel->where(array('id' => $id, 'state' => '3'))->find();
	if (empty($section)) {
	    $response = array('ret' => '1002', 'code' => '未找到选中的号码区间！');
	    return $this->ajaxReturn($response, 'json');
	}
	$start_id = $section['start_id'];
	$end_id = $section['end_id'];
	$data = $numberModel->where(array('user_id' => array('between', array($start_id, $end_id))))->order('user_id desc')->select();
	$i = 0;
	foreach ($data as $key => $value) {
	    if ($value['state'] != '2' || empty($value['app_flag'])) {
		$numberModel->where(array('id' => $value['id']))->delete();
		continue;
	    }
	    $new = $numberModel->where(array('state' => '1', 'user_id' => array('not between', array($start_id, $end_id))))->order('rand()')->find();
	    if (!empty($new)) {
		$new['state'] = '2';
		$new['stime'] = time();
		$new['app_flag'] = $value['app_flag'];
		$new['user_uid'] = $value['user_uid'];
		$result = $numberModel->save($new);
		if ($result) {
		    $numberModel->where(array('id' => $value['id']))->delete();
		    $userinfoModel->where(array('user_uid' => $value['user_uid']))->save(array('user_id' => $new['user_id']));
		}
		$i++;
	    }
	}
	if (!empty($i)) {
	    $sectionModel->commit();
	    $numberModel->commit();
	    $userinfoModel->commit();
	    $response = array('ret' => '1001', 'code' => '纠正成功！');
	    return $this->ajaxReturn($response, 'json');
	} else {
	    $sectionModel->rollback();
	    $numberModel->rollback();
	    $userinfoModel->rollback();
	    $response = array('ret' => '1002', 'code' => '纠正失败！');
	    return $this->ajaxReturn($response, 'json');
	}
    }

}
